<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Noticia extends AdminController {
    
    public function __construct(){
        parent::__construct();
        date_default_timezone_set("America/Sao_Paulo");
    }
    
    public function index($id_menu = null, $page = 0 ){
        $findBy = array();
        $offset = 0;
        if( $page != 0 ) {
            $offset = ( $page - 1 ) * LIMITE_PAGINACAO_ADMIN;
        }

        $lista = $this->doctrine->em->getRepository( 'Noticias' )->findBy(
            $findBy, array('id_noticia' => 'ASC'), LIMITE_PAGINACAO_ADMIN, $offset
        );

        $total = $this->count( 'noticias' );
        
        $this->assign( 'lista', $lista );
        $this->assign( 'total', $total );
        $this->display( 'noticia/index' );
    }
    
    public function editar( $id = null ) {
        if ( !empty( $id ) && $_SERVER['REQUEST_METHOD'] == 'GET' ) {
            $obj = $this->doctrine->em->getRepository( 'Noticias' )->find( $id );
            $_POST = $obj->asArray();
        } else {
            $_POST['ativo'] = true;
        }
        $this->display( 'noticia/editar' );
    }
    
    
    public function novo($id_menu = null){
        redirect('admin/post/editar');
    }
    
    public function save( $id = null ){
        $em = $this->doctrine->em;
        $entity = new Noticias();
        try {
            if( !empty( $id ) ) {
                $entity = $em->getRepository( 'Noticias' )->find( $id );
            }
            populateForm( $entity, $this->input->post() );
            $entity->set_data_inicio_publicacao( new \DateTime( dataToDate( $this->input->post( 'data_inicio_publicacao' ) ) ) );
            $entity->set_data_fim_publicacao( new \DateTime( dataToDate( $this->input->post( 'data_fim_publicacao' ) ) ) );
            if( $this->validate() ){
                $entity->set_data_alteracao( new \DateTime( "now" ) );
                
                $em->persist( $entity );
                $em->flush();
                $this->showSuccess();
                redirect('admin/noticia/index/'. $entity->get_id_noticia());
            } 
        } catch (Exception $ex) {
            $this->showErros($ex);
        }         
        $this->display('noticia/editar');

    }
    
    private function validate(){
        $this->load->helper(array('form', 'url'));
        $this->form_validation->set_rules('titulo', 'Título', 'required');
        $this->form_validation->set_rules('conteudo', 'Conteúdo', 'required');
        return $this->form_validation->run();
    }
}
/* End of file noticia.php */
/* Location: ./application/controllers/admin/noticia.php */